import { ref } from 'vue'
import { adapter, withIgnoreValid } from '@/request'
import { login2ByPost } from '@/core/api/user'
import is from '@/utils/is'
import { useMainStore } from '@/store/useMainStore'
import { message } from 'ant-design-vue'
import type { UserInfo } from '@/core/interfaces/user'
import type { RequestWrapper } from '@/core/interfaces/common'
import { useRegionStore } from '@/store/useRegionStore'

export interface Login2Fields {
  token: string
  userId: number
}

export enum LoginEnum {
  success = 0,
  error = -1
}

export default function login2() {
  const service = adapter<RequestWrapper<UserInfo>>(withIgnoreValid)
  const loading = ref(false)
  const response = ref<UserInfo | undefined>()
  const mainStore = useMainStore()
  const regionStore = useRegionStore()

  const fetch = (data: Login2Fields) => {
    const { url, method } = login2ByPost()
    loading.value = true

    return service({
      config: {
        url,
        method,
        data
      },
      callback: (res) => {
        if (res.data.code === LoginEnum.error) {
          return new Error('用户名或密码错误，请再试一次')
        }
        response.value = res.data.data
        mainStore.setToken(response.value?.token)
        mainStore.setUserInfo(response.value?.content)
        regionStore.initRegion()
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message)
        }
        mainStore.removeToken()
        mainStore.removeUserInfo()
        regionStore.removeRegion()
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [null, fetch, loading] as const
}
